package com.newtouch.xcd.common.to;

import com.newtouch.xcd.common.constants.ResponseCode;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.validation.BindingResult;

import java.io.Serializable;

/**
 * 通用返回对象
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="返回封装对象", description="返回封装对象")
public class CommonResult<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private String code;
    private String message;
    private T data;

    /**
     * 普通成功返回
     */
    public static CommonResult success() {

        CommonResult result = new CommonResult();

        result.setCode(ResponseCode.R200.getCode());
        result.setMessage(ResponseCode.R200.getMessage());
        return result;
    }

    /**
     * 普通成功返回
     * @param data 获取的数据
     */
    public static CommonResult success(Object data) {

        CommonResult result = new CommonResult();

        result.setCode(ResponseCode.R200.getCode());
        result.setMessage(ResponseCode.R200.getMessage());
        result.setData(data);
        return result;
    }

    /**
     * 异常返回
     * @param code  错误码
     * @param message   错误信息
     * @return
     */
    public static CommonResult error(String code,String message) {

        CommonResult result = new CommonResult();
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    /**
     * 参数验证失败使用
     *
     * @param message 错误信息
     */
    public CommonResult validateFailed(String message) {
        this.code = ResponseCode.R407.getCode();
        this.message = message;
        return this;
    }

    /**
     * 参数验证失败使用
     * @param result 错误信息
     */
    public CommonResult validateFailed(BindingResult result) {
        validateFailed(result.getFieldError().getDefaultMessage());
        return this;
    }


}
